require 'json_web_token'

class Api::V1::SessionsController < Api::V1::BaseController
  skip_before_action :authenticate_request!, only: [:create, :wechat]

  def create
    @user = User.find_by(phone: params[:phone])
    
    if @user && @user.authenticate(params[:password])
      @user.update_attributes(registration_id: params[:registration_id])
      @auth_token = JsonWebToken.encode({ user_id: @user.id })
    else
      render json: { result: false, message: '账号不存在或密码错误.' }, status: :ok
    end
  end

  def wechat
    if params[:open_id].presence
      @user = User.find_by(open_id: params[:open_id])
      if @user.blank?
        if params[:phone].blank? || params[:password].blank?
          render json: { result: false, message: "请输入手机号码和密码." }, status: :ok and return
        end
        @user = User.find_by(phone: params[:phone])
        if @user && @user.authenticate(params[:password])
          @user.open_id = params[:open_id]
        else
          @user = User.new
          @user.phone = params[:phone]
          @user.password = params[:password]
          @user.open_id = params[:open_id]
        end
        if not @user.save
          render json: { result: false, message: render_errors(@user.errors.messages) }, status: :ok and return
        end
      end
      @auth_token = JsonWebToken.encode({ user_id: @user.id })
      @user.update_attributes(registration_id: params[:registration_id])
    else
      render json: { result: false, message: '缺少参数.' }, status: :ok
    end
  end

end
